{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Two chained reservoirs\n",
    "\n",
    "Two disconnected electrical loads are fed from two reservoirs linked by a river; the first reservoir has inflow from rain onto a water basin.\n",
    "\n",
    "Note that the two reservoirs are tightly coupled, meaning there is no time delay between the first one emptying and the second one filling, as there would be if there were a long stretch of river between the reservoirs. The reservoirs are essentially assumed to be close to each other. A time delay would require a \"Link\" element between different snapshots, which is not yet supported by PyPSA (but could be enabled by passing network.lopf() an extra_functionality function)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pypsa\n",
    "import pandas as pd\n",
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "\n",
    "from pyomo.environ import Constraint"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "First tell PyPSA that links will have a 2nd bus by overriding the component_attrs. This is needed so that water can both go through a turbine AND feed the next reservoir"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "override_component_attrs = pypsa.descriptors.Dict({k : v.copy() for k,v in pypsa.components.component_attrs.items()})\n",
    "override_component_attrs[\"Link\"].loc[\"bus2\"] = [\"string\",np.nan,np.nan,\"2nd bus\",\"Input (optional)\"]\n",
    "override_component_attrs[\"Link\"].loc[\"efficiency2\"] = [\"static or series\",\"per unit\",1.,\"2nd bus efficiency\",\"Input (optional)\"]\n",
    "override_component_attrs[\"Link\"].loc[\"p2\"] = [\"series\",\"MW\",0.,\"2nd bus output\",\"Output\"]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network = pypsa.Network(override_component_attrs=override_component_attrs)\n",
    "network.set_snapshots(pd.date_range(\"2016-01-01 00:00\",\"2016-01-01 03:00\",freq=\"H\"))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Add assets to the network."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.add(\"Carrier\", \"reservoir\")\n",
    "network.add(\"Carrier\", \"rain\")\n",
    "\n",
    "network.add(\"Bus\", \"0\", carrier=\"AC\")\n",
    "network.add(\"Bus\", \"1\", carrier=\"AC\")\n",
    "\n",
    "network.add(\"Bus\", \"0 reservoir\", carrier=\"reservoir\")\n",
    "network.add(\"Bus\", \"1 reservoir\", carrier=\"reservoir\")\n",
    "\n",
    "\n",
    "network.add(\"Generator\",\n",
    "            \"rain\",\n",
    "            bus=\"0 reservoir\",\n",
    "            carrier=\"rain\",\n",
    "            p_nom=1000,\n",
    "            p_max_pu=[0.,0.2,0.7,0.4])\n",
    "\n",
    "\n",
    "network.add(\"Load\",\n",
    "            \"0 load\",\n",
    "            bus=\"0\",\n",
    "            p_set=20.)\n",
    "\n",
    "network.add(\"Load\",\n",
    "            \"1 load\",\n",
    "            bus=\"1\",\n",
    "            p_set=30.)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The efficiency of a river is the relation between the gravitational potential energy of 1 m^3 of water in reservoir 0 relative to its turbine versus the potential energy of 1 m^3 of water in reservoir 1 relative to its turbine"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.add(\"Link\",\n",
    "            \"spillage\",\n",
    "            bus0=\"0 reservoir\",\n",
    "            bus1=\"1 reservoir\",\n",
    "            efficiency=0.5,\n",
    "            p_nom_extendable=True) \n",
    "\n",
    "\n",
    "#water from turbine also goes into next reservoir\n",
    "network.add(\"Link\",\n",
    "            \"0 turbine\",\n",
    "            bus0=\"0 reservoir\",\n",
    "            bus1=\"0\",\n",
    "            bus2=\"1 reservoir\",\n",
    "            efficiency=0.9,\n",
    "            efficiency2=0.5,\n",
    "            capital_cost=1000,\n",
    "            p_nom_extendable=True)\n",
    "\n",
    "network.add(\"Link\",\n",
    "            \"1 turbine\",\n",
    "            bus0=\"1 reservoir\",\n",
    "            bus1=\"1\",\n",
    "            efficiency=0.9,\n",
    "            capital_cost=1000,\n",
    "            p_nom_extendable=True)\n",
    "   \n",
    "\n",
    "network.add(\"Store\",\n",
    "            \"0 reservoir\",\n",
    "            bus=\"0 reservoir\",\n",
    "            e_cyclic=True,\n",
    "            e_nom_extendable=True) \n",
    "\n",
    "network.add(\"Store\",\n",
    "            \"1 reservoir\",\n",
    "            bus=\"1 reservoir\",\n",
    "            e_cyclic=True,\n",
    "            e_nom_extendable=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.lopf(network.snapshots)\n",
    "print(\"Objective:\",network.objective)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.generators_t.p.plot.area(figsize=(9,4))\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now, let's have  look at the different outputs of the links."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "scrolled": true
   },
   "outputs": [],
   "source": [
    "network.links_t.p0.plot(figsize=(9,4), lw=3)\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.links_t.p1.plot(figsize=(9,4), lw=3)\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "network.links_t.p2.plot(figsize=(9,4), lw=3)\n",
    "plt.tight_layout()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "What are the energy outputs and energy levels at the reservoirs?"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame({attr: network.stores_t[attr][\"0 reservoir\"] for attr in [\"p\",\"e\"]})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "pd.DataFrame({attr: network.stores_t[attr][\"1 reservoir\"] for attr in [\"p\",\"e\"]})"
   ]
  }
 ],
 "metadata": {
  "@webio": {
   "lastCommId": null,
   "lastKernelId": null
  },
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
